﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WebLib.FileUpload
{
    internal class FileUploader
    {
        public string SaveFileObject(byte[] data, string savedDirectory, string fileName, string ext, bool isUniqueName = true)
        {
            using (var imperson = new ImpersonateService())
            {
                try
                {
                    // TODO : 추후 가장해야 함
                    if (!imperson.ImpersonateValidUser(ConfigurationManager.AppSettings["FileUploadUser"], ConfigurationManager.AppSettings["FileUploadDomain"], ConfigurationManager.AppSettings["FileUploadPWD"]))
                        throw new Exception("가장에 실패하였습니다.");

                    if (string.IsNullOrEmpty(savedDirectory)) throw new Exception("Upload Failure!!");

                    if (!Directory.Exists(savedDirectory)) Directory.CreateDirectory(savedDirectory);

                    var fullFileName = (isUniqueName ? GetUniqueFileName(savedDirectory, ext) : Path.Combine(savedDirectory, fileName));

                    File.WriteAllBytes(fullFileName, data);

                    return fullFileName;
                }
                catch
                {
                    return string.Empty;
                }
                finally
                {
                    imperson.UndoImpersonation();
                }
            }
        }

        private string GetUniqueFileName(string dir, string ext)
        {
            var rdmName = Path.GetRandomFileName();
            var fullFilePath = Path.Combine(dir, string.Format("{0}{1}", rdmName, ext));

            while (File.Exists(fullFilePath))
            {
                fullFilePath = Path.Combine(dir, string.Format("{0}{1}", rdmName, ext));
            }

            return fullFilePath;
        }

        internal Task<string> UploadHttpPostedFileObject(HttpPostedFileBase httpPostedFile, string rootDirectory, string directory)
        {
            return Task.Run(() =>
            {
                using (var imperson = new ImpersonateService())
                {
                    System.Diagnostics.Debug.WriteLine("1");
                    // TODO : 추후 가장해야 함
                    if (!imperson.ImpersonateValidUser(ConfigurationManager.AppSettings["FileUploadUser"], ConfigurationManager.AppSettings["FileUploadDomain"], ConfigurationManager.AppSettings["FileUploadPWD"]))
                        throw new Exception("가장에 실패하였습니다.");

                    System.Diagnostics.Debug.WriteLine("2");

                    if (string.IsNullOrEmpty(directory)) throw new Exception("Upload Failure!!");

                    System.Diagnostics.Debug.WriteLine("3 : " + directory);

                    var dir = Path.Combine(rootDirectory, directory);
                    if (!Directory.Exists(directory)) Directory.CreateDirectory(dir);
                    var ext = Path.GetExtension(httpPostedFile.FileName.ToLower());

                    var fullFilePath = GetUniqueFileName(dir, ext);

                    System.Diagnostics.Debug.WriteLine("4 : " + fullFilePath);

                    try
                    {
                        httpPostedFile.SaveAs(fullFilePath);
                    }
                    catch
                    {
                        return string.Empty;
                    }
                    finally
                    {
                        imperson.UndoImpersonation();
                    }

                    return fullFilePath.Replace(rootDirectory + @"\", string.Empty);
                }
            });
        }
    }
}
